package com.cynteka.cyfoman.ui;

import org.apache.commons.chain.*;
import org.apache.commons.chain.Context;
import org.apache.commons.chain.impl.ContextBase;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;

import javax.swing.*;
import java.awt.event.ActionEvent;

/**
 * User: Sergey
 * Date: 09.08.11
 * Time: 15:46
 */
public abstract class AbstractChainAction extends AbstractAction implements BeanFactoryAware {
    private Catalog catalog;
    private BeanFactory beanFactory;

    protected AbstractChainAction() {
    }

    protected AbstractChainAction(String name) {
        super(name);
    }

    protected AbstractChainAction(String name, Icon icon) {
        super(name, icon);
    }

    protected void initCatalog() {
        if(catalog == null) {
            catalog = (Catalog) beanFactory.getBean(Catalog.CATALOG_KEY);
        }
    }

    public Catalog getCatalog() {
        return catalog;
    }

    public void setCatalog(Catalog catalog) {
        this.catalog = catalog;
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

    @Override
    public final void actionPerformed(ActionEvent e) {
        String name = (String) getValue(Action.NAME);
        initCatalog();
        Command cmd = getCatalog().getCommand(name);

        if(cmd != null) {
            org.apache.commons.chain.Context context = createContext();
            try {
                cmd.execute(context);
            } catch (Exception ex) {
                // TODO handle it
                ex.printStackTrace();
            }
        } else {
            // TODO warn it
        }

    }

    protected Context createContext() {
        return new ContextBase();
    }

    protected BeanFactory getBeanFactory() {
        return beanFactory;
    }
}
